<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>练习：自定义指令，鼠标拖动</title>
    <script src="js/vue.js"></script>
    <style>
        #itany div{
            width: 100px;
            height: 100px;
            position:absolute;
        }
        #itany .hello{
            background-color:red;
            top:0;
            left:0;
        }
        #itany .world{
            background-color:blue;
            top:0;
            right:0;
        }

    </style>
</head>
<body>
    <div id="itany">
        <div class="hello" v-drag>计科一班</div>
        <div class="world" v-drag>纳恩博</div>
    </div>

    <script>
        //自定义全局指令
        Vue.directive('drag',function (el) {
            //绑定和更新时触发
            //onmousedown 当鼠标点击时触发
            el.onmousedown = function (e) {
                console.log('1111');
                //获取鼠标点击处分别与div左边和div上边的距离：鼠标位置 - div位置
                var disX = e.clientX - el.offsetLeft;
                var disY = e.clientY - el.offsetTop;

                //包含在onmousedown里面，必须写在这里面，表示点击后才移动，为防止鼠标移出div，使用document.onmousemove
                document.onmousemove = function (e) {
                    //获取移动后div的位置：鼠标位置 - disX 或 disY
                    var l = e.clientX - disX;
                    var t = e.clientY - disY;

                    el.style.left = l + 'px';
                    el.style.top = t + 'px';
                }

                //停止移动，将document.onmousemove置为空即可
                //onmouseup : 鼠标点击松开时触发
                document.onmouseup = function (e) {
                    document.onmousemove = null;
                    document.onmouseup = null;
                }
            }
        });

        var vm = new Vue({
            el : '#itany'
        });
    </script>
</body>
</html>